package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();//得到请求路径
        log.info("请求了路径：{}", url);
        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");
        //4. 判断令牌是否存在，
        if(!StringUtils.hasLength(token)){
            log.info("请求头中无token");
            //如果不存在，响应 401
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //5. 解析token，
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("解析到token中的信息：{}", claims);
        } catch (Exception e) {
            log.error("解析token失败", e);
            //如果解析失败，响应 401
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //6. 放行
        log.info("令牌校验通过，放行");
        return true;
    }
}
